# cython: language_level=3
import os
from datetime import datetime

import json
from dotenv import load_dotenv
from sqlalchemy.orm import Session

from app.db.redis.invitation import set_resource_plan_to_redis
from app.models import Invitation, MrLine, BaseLine
from app.schemas.platform import GetInvitationRequest
from common.log import get_logger
from common.time import get_datetime_now

load_dotenv()
CREDIT_CODE = os.getenv("CREDIT_CODE")
logger = get_logger('server')


def save_invitations(db: Session, payload: GetInvitationRequest):
    """
    保存邀约信息，主站请求中的一部分信息
    """
    intra_day_task = Invitation(
    #  邀约计划id，string
        invitation_id=payload.invitationId,
    #  邀约时间
        invitation_time=datetime.strptime(payload.invitationTime, "%Y-%m-%d %H:%M:%S"),
    #  邀约截止答复时间
        reply_time=datetime.strptime(payload.replyTime, "%Y-%m-%d %H:%M:%S"),
    #  响应开始执行时间
        start_time=datetime.strptime(payload.startTime, "%Y-%m-%d %H:%M:%S"),
    #  响应执行结束时间
        end_time=datetime.strptime(payload.endTime, "%Y-%m-%d %H:%M:%S"),
    #  符合邀约调节的resourceID，字符串类型，以逗号分隔，，all表示全部的资源都参与
       invite_range=payload.inviteRange,
    #  邀约类型，string
        #  交易品种，
            # 精准响应削峰：RQXF；
            # 精准响应填谷：RQTG；
            # 南网辅助服务：NWFZFW。
        exchange_type=payload.exchangeType,
    #  保存邀约时间 
        create_time=get_datetime_now(),
    )
    # 将普通邀约信息存起来（mysql），1对应数据库的invitation表
    db.add(intra_day_task)
    mr_line = payload.mrLine
    base_lines = payload.baseLine

        # 将主站邀约的需求曲线储存到数据库中,对应数据库的mr_line表
    for key, value in mr_line.items():
        logger.info(f"Key: {key}, Value: {value}")
        temp = MrLine(invitation_id=payload.invitationId, key=key, value=value)
        db.add(temp)

    response_plan = []
    for base_line in base_lines:
        temp_plan = {
            "resourceId": base_line["resourceId"],
            "responseLine": {}
        }#把主站发的基线负荷数据存到数据库中
        for key, value in base_line.items():
            if key != "resourceId":
                temp = BaseLine(
                    invitation_id=payload.invitationId,
                    key=key,
                    value=value,
                    resource_id=base_line["resourceId"],
                )
                db.add(temp)
                temp_plan["responseLine"].update({key: value})

        response_plan.append(temp_plan)
    set_resource_plan_to_redis(json.dumps(response_plan))
    db.commit()


"""
base_lines = [
    {"resourceId": "resource1", "otherData": "data1"},
    {"resourceId": "resource2", "otherData": "data2"},
    # 更多条目...
]

temp_plan:
{
    "resourceId": "resource1",
    "responseLine": {}
}


response_plan:
[
    {
        "resourceId": "resource1",
        "responseLine": {}
    },
    {
        "resourceId": "resource2",
        "responseLine": {}
    },
    # 更多基于base_lines条目的字典...
]

"""


